﻿(function (window) {

    var niggles = {};

    niggles._snippets = {}; // snippets rendered to the page
    niggles._handlers = new Array(); // handlers
    niggles._loginToken = '';
    niggles._controller = new Controller();

    niggles.init = function () {
        $(function () { niggles.load(); });
    };

    niggles.load = function () {
        $('.snippet').each(function () { niggles._snippets[this.id] = this; });
        $(niggles._handlers).each(function () { this.Initialise(niggles); });

        niggles._snippets.menu.Execute();
        niggles._snippets.login.Execute();
        niggles._snippets.card.Execute();
    };

    niggles.Register = function (snippetHandler) {
        niggles._handlers.push(snippetHandler);
    }

    niggles.SetLoginToken = function (token) {
        niggles._loginToken = token;
        $('#welcome-banner').text('Current user: ' + token);
    }

    niggles.Authorize = function (path) {
        if (niggles._loginToken == null) return false;
        if (niggles._loginToken == '') return false;
        return true;
    }

    niggles.ServiceAgent = new ServiceAgent("");

    window.niggles = niggles;
    window.niggles.init();

})(window);

function Controller() {
    this.NavTo = function (whereTo) {
        if (niggles.Authorize(whereTo)) 
        {
            var path = whereTo.split("/");
            var controller = this[path[1]];
            if (controller != null) {
                controller.Execute(niggles, path);
            }
        }
    }
}